package org.yan.kangaroo.auth.config.security.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;
import org.yan.kangaroo.auth.config.security.SecurityConstant;
import org.yan.kangaroo.auth.constant.response.ResponseCodeEnum;
import org.yan.kangaroo.common.response.ResponseUtils;
import org.yan.kangaroo.common.response.Result;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangx
 * @date 11/11/2019 15:13
 */
@Slf4j
@Configuration
public class CaptchaValidateFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String requestUrl = request.getRequestURI();

        if (StringUtils.equalsAnyIgnoreCase(SecurityConstant.LOGIN_URL, requestUrl)) {
            String captchaId = request.getParameter("captchaId");
            String code = request.getParameter("code");
            if (StringUtils.isBlank(captchaId) || StringUtils.isBlank(code)) {
                Result result = Result.error(ResponseCodeEnum.CAPTCHA_PARAMS_DEFECT);
                ResponseUtils.outAsJson(response, result);
                return;
            }
            String redisCode = redisTemplate.opsForValue().get(captchaId);
            if (StringUtils.isBlank(redisCode)) {
                ResponseUtils.outAsJson(response, Result.error(ResponseCodeEnum.VERIFY_CODE_INVALID));
                return;
            }

            if (!redisCode.toLowerCase().equals(code.toLowerCase())) {
                log.info("验证码错误：code:" + code + "，redisCode:" + redisCode);
                ResponseUtils.outAsJson(response, Result.error(ResponseCodeEnum.VERIFY_CODE_INPUT_ERROR));
                return;
            }
            // 已验证清除key
            redisTemplate.delete(captchaId);
            // 验证成功 放行
            chain.doFilter(request, response);
            return;
        }
        chain.doFilter(request, response);
    }
}
